package com.jyu.apts.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.jyu.apts.dto.PermissionDto;
import com.jyu.apts.dto.ResultDto;
import com.jyu.apts.entity.Permission;
import com.jyu.apts.entity.Role;
import com.jyu.apts.service.PermissionService;
import com.jyu.apts.service.RoleService;

@RestController
public class RolePermissionController {
	
	@Autowired
	RoleService roleService;
	
	@Autowired
	PermissionService permissionService;
	
	@RequiresPermissions("role_permission_html")
	@RequestMapping("/role_permission_html")
	ModelAndView role_permission_html() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/role_permission.html");
		return mv;
	}
	
	@RequiresPermissions("role_permission_html")
	@RequestMapping("/role_permission_up")
	public  ResultDto role_permission_up(String role_ids,String perm_ids) {
		List<Long> lPerm_ids = new ArrayList<Long>();
		if(perm_ids.trim().length()!=0) {
			String[] perm_idsArray = perm_ids.split(",");
			for(String perm_id : perm_idsArray) {
				lPerm_ids.add(new Long(perm_id));
			}
		}
		List<Permission> perms = permissionService.findAllById(lPerm_ids);
		
		String[] role_idsArray = role_ids.split(",");
		List<Long> lRole_ids = new ArrayList<Long>();
		for(String role_id : role_idsArray) {
			lRole_ids.add(new Long(role_id));
		}
		List<Role> roles = roleService.findAllById(lRole_ids);
		
		for(Role role : roles) {
			role.setPermissions(perms);
		}
		roleService.save(roles);
		
		return new ResultDto("授权成功",null,0);
	}
	
	@RequiresPermissions("role_permission_html")
	@RequestMapping("/getPermissionsByRoles")
	public List<PermissionDto> getPermissionByRole(String role_ids){
		List<PermissionDto> permDtos = new ArrayList<PermissionDto>();
		if(role_ids.trim().length()==0)
			return permDtos;
		String[] role_idsArray = role_ids.split(",");
		List<Long> lRole_ids = new ArrayList<Long>();
		for(String role_id : role_idsArray) {
			lRole_ids.add(new Long(role_id));
		}
		List<Role> roles = roleService.findAllById(lRole_ids);
		
		for(Role role : roles) {
			List<Permission> perms = role.getPermissions();
			for(Permission perm : perms) {
				PermissionDto permDto = new PermissionDto().convert(perm);
				if(!permDtos.contains(permDto)) {
					permDtos.add(permDto);
				}
			}
		}
		return permDtos;
	}
	
}
